package net.bat.web.zxzx;

import java.util.List;

import net.bat.dto.MessageDTO;
import net.bat.entity.Message;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

//Spring Bean的标识.
@Component
// 类中所有public函数都纳入事务管理的标识.
@Transactional
public class ZxzxService {
	@Autowired
	private ZxzxDao dao;

	public Page<Message> getMessage(int pid, int pageNumber, int pageSize, String sortType) {
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
		Page<Message> r = dao.findByPid(pid, pageRequest);
		return r;
	}
	
	public Page<Message> getJidMessage(int jid, int pageNumber, int pageSize, String sortType) {
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
		Page<Message> r = dao.findByJid(jid, pageRequest);
		return r;
	}

	public void saveMessage(Message vo) {
		dao.save(vo);
	}

	public List<MessageDTO> getMessage(int pid) {
		return dao.findByPid(pid);
	}

	public Message findMessage(int id) {
		return dao.findById(new Long(id));
	}

	private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		} else if ("dtCreate".equals(sortType)) {
			sort = new Sort(Direction.DESC, "dtCreate");
		}
		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

}
